package com.aidex.system.service;

import com.aidex.common.constant.Constants;
import com.aidex.common.utils.http.HttpUtils;
import com.aidex.request.JieBaAddWordsRequest;
import com.aidex.response.NlpCutResponse;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 处理NLP分词
 *
 * @author jmy
 * @version 1.1
 * @date 2021-10-06 10:20
 */
@Service
public class NlpService {

    @Value("${nlp.url}")
    private String url;

    private static final List<String> N = Arrays.asList(new String[]{"n", "nz", "ns", "vn", "nr", "nt", "nw"});

    /**
     * 没有锂电池的过滤掉
     */
    private static final List<String> NO_LDC = Arrays.asList(new String[]{
        "无电池",
        "没有电池",
        "无锂电池",
        "没有锂电池",
        "不含锂电池"
    });

    /**
     * 分词并获取返回的名词性结果
     *
     * @param message
     * @return
     */
    public List<String> getCutList(String message) {
        for (String s : NO_LDC) {
            message = message.replace(s, "");
        }
        String resp = null;
        try {
            resp = HttpUtils.sendGet(url + "/nlp/jieba/cut", "text=" + URLEncoder.encode(message, Constants.UTF8));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        NlpCutResponse response = JSON.parseObject(resp, NlpCutResponse.class);
        List<String> words = new ArrayList<>();
        for (NlpCutResponse.Result result : response.getData()) {
            // 判断词性，如果是名词类，提取出来
            if (N.contains(result.getFlag())) {
                words.add(result.getWord());
            }
        }
        if (words.isEmpty()) {
            words.add(message);
            return words;
        }
        return words;
    }

    /**
     * 添加自定义词库
     *
     * @param word
     */
    public void addWord(String word) {
        JieBaAddWordsRequest request = new JieBaAddWordsRequest();
        request.setWord(word);
        request.setFreq(9999);
        request.setTag("n");
        HttpUtils.sendPost(url + "/nlp/jieba/add", JSON.toJSONString(request));
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        String resp = null;
        try {
            resp = HttpUtils.sendGet("http://localhost:8000/nlp/jieba/cut", "text=" + URLEncoder.encode("线束 线路板  数据线 塑胶壳  铁制模块", Constants.UTF8));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        NlpCutResponse response = JSON.parseObject(resp, NlpCutResponse.class);
        List<String> words = new ArrayList<>();
        for (NlpCutResponse.Result result : response.getData()) {
            // 判断词性，如果是名词类，提取出来
            if (N.contains(result.getFlag())) {
                words.add(result.getWord());
            }
        }
    }

}
